package com.example.demo.core.web.core.filter;

import com.example.demo.core.web.core.enums.GlobalErrorCodeConstants;
import com.example.demo.core.web.core.exception.ServerException;
import com.example.demo.core.web.core.exception.ServiceException;
import com.example.demo.core.web.core.model.CommonResult;
import org.noear.solon.Solon;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;

/**
 * @author airhead
 */
public class DemoExceptionFilter implements Filter {
  @Override
  public void doFilter(Context ctx, FilterChain chain) {
    boolean debugMode = Solon.cfg().isDebugMode();

    try {
      chain.doFilter(ctx);
    } catch (ValidatorException e) {
      if (debugMode) {
        e.printStackTrace();
      }

      ctx.status(e.getCode());
      ctx.outputAsJson(CommonResult.error(e.getCode(), e.getMessage()).toJson());
    } catch (ServerException e) {
      if (debugMode) {
        e.printStackTrace();
      }

      ctx.status(e.getCode());
      ctx.outputAsJson(CommonResult.error(e.getCode(), e.getMessage()).toJson());
    } catch (ServiceException e) {
      if (debugMode) {
        e.printStackTrace();
      }

      ctx.status(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
      ctx.outputAsJson(CommonResult.error(e.getCode(), e.getMessage()).toJson());
    } catch (Throwable e) {
      if (debugMode) {
        e.printStackTrace();
      }

      ctx.status(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
      ctx.outputAsJson(CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR).toJson());
    }
  }
}
